package com.edward.weather.service;

import com.edward.weather.strategy.WeatherApiContext;
import com.edward.weather.strategy.WeatherApiStrategy;
import com.edward.weather.vo.request.WeatherRequestVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.edward.weather.model.WeatherData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeatherService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private WeatherApiContext apiContext;

    @Autowired
    private Map<String, WeatherApiStrategy> weatherApiStrategyMap;

    private static final String WEATHER_CACHE_KEY = "weather:";
    private static final long CACHE_DURATION = 2; // 缓存时间2小时


    private <T> T getCache(String cacheKey,Class<T> tClass){
        // 尝试从Redis获取缓存数据
        String cachedData = redisTemplate.opsForValue().get(cacheKey);
        if (cachedData != null) {
            try {
                return objectMapper.readValue(cachedData, tClass);
            } catch (Exception e) {
                // 如果解析缓存数据失败，继续获取新数据
            }
        }
        return null;

    }

    private void setCache(String cacheKey,Object obj){
        // 存入Redis缓存
        try {
            redisTemplate.opsForValue().set(
                    cacheKey,
                    objectMapper.writeValueAsString(obj),
                    CACHE_DURATION,
                    TimeUnit.HOURS
            );
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取天数的天气
     * @param weatherRequestVO
     * @return
     */
    public WeatherData dayWeather(WeatherRequestVO weatherRequestVO) {
        String cacheKey = WEATHER_CACHE_KEY+":day:"+ weatherRequestVO.getDay() +":"+weatherRequestVO.getLocationId();

        WeatherData cacheData = getCache(cacheKey, WeatherData.class);
        if (cacheData != null){
            return cacheData;
        }

        // 调用OpenWeatherMap API  1,000次/天

        //高德的api 5000次/日左右 https://lbs.amap.com/api/webservice/guide/api/weatherinfo
        WeatherData weatherData = apiContext.dayWeather(weatherRequestVO);

        setCache(cacheKey,weatherData);
        return weatherData;
    }
    public WeatherData getWeatherData(String city) {
        String cacheKey = WEATHER_CACHE_KEY + city;

        WeatherData cacheData = getCache(cacheKey, WeatherData.class);
        if (cacheData != null){
            return cacheData;
        }

        // 调用OpenWeatherMap API  1,000次/天

        //高德的api 5000次/日左右 https://lbs.amap.com/api/webservice/guide/api/weatherinfo
        WeatherData weatherData = apiContext.fetchWeather(city);

        setCache(cacheKey,weatherData);
        return weatherData;
    }

    private WeatherData parseWeatherData(String jsonResponse) {
        try {
            // 这里需要根据OpenWeatherMap的响应格式解析数据
            // 这是简化版的实现，实际需要更详细的解析逻辑
            WeatherData weatherData = new WeatherData();
            // ... 解析JSON数据到weatherData对象
            return weatherData;
        } catch (Exception e) {
            throw new RuntimeException("解析天气数据失败", e);
        }
    }


    public WeatherData indices(WeatherRequestVO weatherRequestVO) {

        String cacheKey = WEATHER_CACHE_KEY +":indices:" + weatherRequestVO.getDay() +":"+weatherRequestVO.getLocationId();

        WeatherData cacheData = getCache(cacheKey, WeatherData.class);
        if (cacheData != null){
            return cacheData;
        }

        // 调用OpenWeatherMap API  1,000次/天

        //高德的api 5000次/日左右 https://lbs.amap.com/api/webservice/guide/api/weatherinfo
        WeatherData weatherData = apiContext.indices(weatherRequestVO);

        setCache(cacheKey,weatherData);
        return weatherData;
    }
}